from collections import deque

def parse_player(input: str):
    player = deque()
    for line in input.splitlines()[1:]:
        player.append(int(line))
    return player

with open('input.txt') as file:
    parts = file.read().split('\n\n')
    player1 = parse_player(parts[0])
    player2 = parse_player(parts[1])

    while len(player1) != 0 and len(player2) != 0:
        top1, top2 = player1.popleft(), player2.popleft()
        if top1 > top2:
            player1.append(top1)
            player1.append(top2)
        else: 
            player2.append(top2)
            player2.append(top1)

    winner = player1 if len(player1) != 0 else player2

    print( sum(v * (i + 1) for (i, v) in enumerate(reversed(winner))) )